#include "order.h"
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;

Order::Order(const string& _trainID, const string& _passengerName, 
            const string& _passengerID, const string& _phoneNumber)
    : trainID(_trainID), passengerName(_passengerName),
      passengerID(_passengerID), phoneNumber(_phoneNumber) {
}

void Order::showOrderInfo(){
    cout << "订单号: " << orderID << endl;
    cout << "车次: " << trainID << endl;
    cout << "乘客姓名: " << passengerName << endl;
    cout << "乘客身份证号: " << passengerID << endl;
    cout << "乘客电话号码: " << phoneNumber << endl;
}

void OrderList::searchOrder(const int& orderID){
    for(auto order = orders.begin(); order != orders.end(); ++order){
        if(order->getOrderID() == orderID){
            order->showOrderInfo();
        }
    }
}

void OrderList::showAllOrders(){
    for(auto order = orders.begin(); order != orders.end(); ++order){
        order->showOrderInfo();
        cout << "--------------------------------" << endl;
    }
}

void OrderList::addOrder(Order& order){
    order.setOrderID(nextId);
    nextId++;
    orders.push_back(order);
}

void OrderList::saveOrders2File(){
    ofstream file("./files/orders.txt" , std::ios::trunc);
    if (!file.is_open()) {
        std::cerr << "错误：无法打开文件 orders.txt" << std::endl;
        return;
    }
    for(auto& o : orders){
        file << o.getOrderID() << "|" << 
        o.getTrainID() << "|" << 
        o.getPassengerName() << "|" << 
        o.getPassengerID() << "|" << 
        o.getPhoneNumber() << endl;
    }
    file.close();
}

void OrderList::loadOrdersFromFile(){
    ifstream file("./files/orders.txt");
    string _orderID, trainID, passengerName, passengerID, phoneNumber, line;
    while(getline(file, line)){
        stringstream ss(line);
        getline(ss, _orderID, '|');
        getline(ss, trainID, '|');
        getline(ss, passengerName, '|');
        getline(ss, passengerID, '|');
        getline(ss, phoneNumber);
        int orderID = stoi(_orderID);
        Order o(trainID, passengerName, passengerID, phoneNumber);
        o.setOrderID(orderID);
        orders.push_back(o);
    }
}

OrderList::OrderList() {
    loadOrdersFromFile();
}